package com.jihox.abookpro;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.NetStatus;
import com.jihox.abookpro.util.PictureUtil;
import com.jihox.abookpro.view.JHProgressDialog;

public class ShareActivity extends Activity  {

	private String shareImagePath = null;

	private String shareTitle;
	private String shareText;
	private String shareLinkUrl=null;
	private String shareplatform;
	
	private RelativeLayout rlShare = null;
	private BookProject bookProject;
	private String worksn;
	private JHProgressDialog pd;
	
	@Override  
	protected void onResume() {     
		super.onResume();  
		
	} 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
			setContentView(R.layout.share_activity);
		else 
			setContentView(R.layout.share_activity_vertical);
		
		MyApplication application = MyApplication.getInstance();
		bookProject = application.getBookProject();
		
		worksn = application.getWorksn();

		//coverBitmap = BitmapFactory.decodeFile(coverImagePath);
		rlShare = (RelativeLayout)findViewById(R.id.llShare);
		//Bitmap bm = PictureUtil.readBitMap(getApplicationContext(), R.drawable.bg_share);
		BitmapDrawable bd = new BitmapDrawable(getResources(), createBackgroundBitmap());
		rlShare.setBackgroundDrawable(bd);
		
		ShareSDK.initSDK(this);
		
		Button btnColse = (Button) findViewById(R.id.btnClose);
		btnColse.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		Button btnWechat = (Button) findViewById(R.id.btnWechat);
		btnWechat.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {				
				clickToUpload(Wechat.NAME);
			}
		});

		Button btnWechatMoments = (Button) findViewById(R.id.btnWechatMoments);
		btnWechatMoments.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				clickToUpload(WechatMoments.NAME);
			}
		});

		Button btnQZone = (Button) findViewById(R.id.btnQZone);
		btnQZone.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				clickToUpload(QZone.NAME);
			}
		});

		Button btnWeibo = (Button) findViewById(R.id.btnWeibo);
		btnWeibo.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				clickToUpload(SinaWeibo.NAME);
			}
		});
	}
	
	Runnable getShareTextRunnable = new Runnable() {
		@Override
		public void run() {
			prepareShareContent();
			String tif[] = bookProject.getBook().getTemplateName().split("_");
			String templateid = tif[2];
			String url = ConfigProperties.getShareText()+templateid;
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			UserHelper helper = new UserHelper();
			get.setHeader("username", helper.getUserName());
			get.setHeader("password", helper.getPassword());
			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				HttpResponse response = httpclient.execute(get);
				HttpEntity resEntity = response.getEntity();
				
				if (resEntity != null) {
					
					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
			
					JSONObject result;
					result = new JSONObject(res);
					shareTitle = result.getString("title");
					shareText = result.getString("text");
					
					resEntity.consumeContent();
				}else{
					data.putString("Error", getResources().getString(R.string.T_NoNet));
				}
			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (ParseException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (JSONException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (Exception e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} finally {
				msg.setData(data);
				getShareTextHandler.sendMessage(msg);
				httpclient.getConnectionManager().shutdown();
			}
		}
	};
	
	Handler getShareTextHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();
			pd.dismiss();
			String error = data.getString("Error");
			if (error != null && !error.isEmpty()) {
				showToast(error);
			}else{
				//分享
				if(Wechat.NAME.equals(shareplatform)){
					shareToWechat(Wechat.NAME);
				}else if(WechatMoments.NAME.toString().equals(shareplatform)){
					shareToWechat(WechatMoments.NAME);
				}else if(QZone.NAME.equals(shareplatform)){
					showShare(QZone.NAME);
				}else if(SinaWeibo.NAME.equals(shareplatform)){
					showShare(SinaWeibo.NAME);
				}
			}
		}
	};

	private void prepareShareContent(){
		shareLinkUrl=ConfigProperties.getShareLinkUrl() + worksn;
		Bitmap shareBitmap = null;
		
		if (bookProject.getBook().getProduct().getCategory()==1){
			shareBitmap = PictureUtil.getBitmapFromAssetsFile(getApplicationContext(), "qZoneShare.png");
		}else{
			shareBitmap = PictureUtil.getBitmapFromAssetsFile(getApplicationContext(), "qZoneShare_calendar.png");
		}
		
		//保存文件
		shareImagePath=Environment.getExternalStorageDirectory()+"/jihox/share.png";
		File f = new File(shareImagePath);	
		try {
			FileOutputStream out = new FileOutputStream(f);
			shareBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		shareBitmap.recycle();
	}
	
	private Bitmap createBackgroundBitmap(){
		if (bookProject.getBook().getProduct().getCategory()==2){
			return PictureUtil.getBitmapFromAssetsFile(getApplicationContext(), "bg_share_calendar.png");
		}else{
			return PictureUtil.getBitmapFromAssetsFile(getApplicationContext(), "bg_share.png");
		}
	}
	
	/////
	// weixin 好友分享与weixin 朋友圈分享
	// change: Rong Time: 7/4 2014
	////
	private void shareToWechat(String platformName){
		OnekeyShare oks = new OnekeyShare();
		//关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setPlatform(platformName);
		oks.setTitle(shareTitle);
		if(Wechat.NAME.equals(platformName)){
			oks.setText(shareText);
		}else if(WechatMoments.NAME.equals(platformName)){
			oks.setText("");
		}
		oks.setUrl(shareLinkUrl);

		oks.setImagePath(shareImagePath);
		oks.show(this);	
	}
	
	///////
	// Qzone 分享与weibo 分享
	//
	// Change: Rong Time: 7/4 2014
	//////
	private void showShare(String platformName) {
		OnekeyShare oks = new OnekeyShare();
		//关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setPlatform(platformName);
		
		
		if(platformName.equals(SinaWeibo.NAME)){
			oks.setText(shareText+shareLinkUrl);
		}
		//分享到Qzone
		else if(platformName.equals(QZone.NAME))
		{	
			oks.setTitle(shareTitle);
			oks.setText(shareText);
			oks.setTitleUrl(shareLinkUrl);
			Log.i("msg_url", shareLinkUrl);

		}
	
		oks.setImagePath(shareImagePath);
		oks.show(this);
	}	

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onDestroy() {
		
		if(shareImagePath!=null&&shareImagePath.length()>0){
			File LastFile=new File(shareImagePath);
			if(LastFile.exists())
				LastFile.delete();
		}
		
		BitmapDrawable bdShareBackground = (BitmapDrawable)rlShare.getBackground();
		rlShare.setBackgroundResource(0);
		bdShareBackground.setCallback(null);
		bdShareBackground.getBitmap().recycle();
		
		super.onDestroy();
	}
		
		Toast toast = null;
		protected synchronized void showToast(String message) {
			if(toast==null)
				toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
			else 
				toast.setText(message);
			toast.show();
		}
		
		//点击启动进度框
		private void clickToUpload(String platform){
			if (NetStatus.getNetState(getApplicationContext()) == NetStatus.NET_NOT_PREPARE) {
				showToast(getResources().getString(R.string.T_Net_Not_Support));
				return;
			}
			//记录当前的分享平台
			shareplatform = platform;
			
			if (shareImagePath==null){
				pd = JHProgressDialog.show(ShareActivity.this, null,
						getResources().getString(R.string.T_Loading_short));
				new Thread(getShareTextRunnable).start();
			}else{
				//分享
				if(Wechat.NAME.equals(shareplatform)){
					shareToWechat(Wechat.NAME);
				}else if(WechatMoments.NAME.toString().equals(shareplatform)){
					shareToWechat(WechatMoments.NAME);
				}else if(QZone.NAME.equals(shareplatform)){
					showShare(QZone.NAME);
				}else if(SinaWeibo.NAME.equals(shareplatform)){
					showShare(SinaWeibo.NAME);
				}
			}
		}
		
}
